#include "serial_driver.h"
#include "messaging.h"
#include <string.h>
void initialize();
void init_pins();

extern volatile UartRxBuffer_s gRxBuffer;   //global rx buffer

/*#define DOOR_OPEN_STRING "res: door open\n"
#define DOOR_CLOSED_STRING "res: door closed\n"
#define START_STRING "Starting...\n"
*/

const char DOOR_OPEN_STRING[] = "rsp: door open\n";
const char DOOR_CLOSED_STRING[] = "rsp: door closed\n";
const char START_STRING[] = "Starting...\n";

#define START_STRING_LEN 12
#define DOOR_OPEN_LEN 15
#define DOOR_CLOSED_LEN 17

char send_buffer[17];

int main()
{
   int total_sent = 0;
   int ret_status=0;
     
   initialize();
   eint();
    
   Uart_TimerA_Init(9600);

   //strncpy(&send_buffer[0],START_STRING, START_STRING_LEN);
   //ensure we are not transmitting
   //while(gCritical == 0x01) { }
   
   while(total_sent < START_STRING_LEN)
   {
      ret_status = Uart_Tx_Buffer((uint8_t*)&START_STRING[total_sent], START_STRING_LEN - total_sent);
      total_sent = ret_status + total_sent;
   }
   
   total_sent = 0;
   while(1) 
   {
      total_sent = 0;
      if(gRxBuffer.mTailPtr != gRxBuffer.mHeadPtr) 
      {
          //P1OUT = 0x01;   //Turn on led temporary check
         ret_status = ProcessByte(gRxBuffer.mData[gRxBuffer.mTailPtr++%4]);
         if(ret_status == RET_STATUS_CLOSED)
         {
            while(total_sent < DOOR_CLOSED_LEN)
            {
               ret_status = Uart_Tx_Buffer((uint8_t*)&DOOR_CLOSED_STRING[total_sent], DOOR_CLOSED_LEN - total_sent);
               total_sent = ret_status + total_sent;
            }
         }
         else
         {
            if(ret_status == RET_STATUS_OPEN)
            {
               while(total_sent < DOOR_OPEN_LEN)
               {
                  ret_status = Uart_Tx_Buffer((uint8_t*)&DOOR_OPEN_STRING[total_sent], DOOR_OPEN_LEN - total_sent);
                  total_sent = ret_status + total_sent;
               }
            }
         }

      }
   }
   
   return 1;
}

//Turn off watchdog and set clock to 1Mhz
void initialize()
{
   WDTCTL = WDTPW + WDTHOLD;               // Stop watchdog timer

   DCOCTL = 0x00;                          // Set DCOCLK to 1MHz
   BCSCTL1 = CALBC1_1MHZ;
   DCOCTL = CALDCO_1MHZ; 
   
   init_pins();
}

void init_pins()
{
   P1OUT = 0x00;                           // Initialize all GPIO
   P1DIR = 0xFF & ~(RX_PIN | GARAGE_SWITCH_PIN);               // Set all pins but RXD to output and garage door switch
   P1REN = GARAGE_SWITCH_PIN;  //Enable pullup/pulldown resistor
   P1OUT = GARAGE_SWITCH_PIN; //set to pull up
   P1SEL = RX_PIN + TX_PIN;            // Timer function for TXD/RXD pins
   P2OUT = 0x00;
   P2SEL = 0x00;
   P2DIR = 0xFF;
}


